/**
 * Tiem: 2023-1-17
 * FileName: Vehicle Detail(车辆详情，新增，修改)
 * Editor: Haidong
 */

import React, { Component } from "react";
import { Form, Input, Button, Space, Select, Divider, Modal } from "antd";
import { CaretDownOutlined } from "@ant-design/icons";
import TheUpload from "@/components/TheUpload";
import TheImage from "@/components/TheImage";
import GoBack from '@/components/TheGoBack';
import { apiPostCarInfo, apiPutCarInfo, apiGetCarInfo, apiPostChauffeurPage } from "@/request/petTaxi"
import "../style/index.less";
import ChauffeurDetail from "./chauffeurDetail"
export default class VehicleDetail extends Component {
    constructor(props) {
        super();

        this.ChauffeurDetailRefs = React.createRef()
        this.state = {
            visible: true,
            id: '',
            type: '',
            content: "",
            chauffeurList: [],
            fileList: [],
            disabled: false,
            picture: '',
            data: '',
            ModalVisible: false
        }
    }

    //Initialization
    componentDidMount() {
        this.setState({
            id: this.props.match.params.id,
            type: this.props.match.params.type
        }, () => {
            if (this.state.id === "add") {
                this.setState({ content: "新增车辆" })
            } else {
                if (this.state.type === "edit") {
                    this.setState({ content: "编辑车辆" })
                } else {
                    this.setState({
                        content: "查看车辆",
                        visible: false,
                        disabled: true,
                    })
                }
                this.getData(this.state.id)
            }
            this.getChauffeurList()
        })

    }

    //CTRL
    //获取信息
    getData = async (carId) => {
        await apiGetCarInfo(carId).then(
            res => {
                if (res.code === 0 && res.data) {
                    let data = res.data
                    let driverId = res.data.driverId
                    let fileList = data.picture.split(',').map((v, k) => {
                        return {
                            name: 'image',
                            uid: k + 1,
                            url: v,
                            status: 'done'
                        }
                    })
                    this.setState({
                        fileList,
                        driverId,
                        picture: data.picture
                    })
                    this.formRef.setFieldsValue(data)
                }
            }
        ).catch(err => {
            React.$message({
                type: 'warning',
                content: err.code
            })
        })
    }
    //获取司机列表
    getChauffeurList = async () => {
        await apiPostChauffeurPage({ pageNo: 1, pageSize: '-1', status: 1, })
            .then(res => {
                if (res.code === 0 && res.data) {
                    this.setState({
                        chauffeurList: res.data
                    })
                }
            })
    }
    // 车辆图片
    getFileResult = value => {
        let arr = value.map(v => {
            let data = ''
            if (v.response && v.response.code === 0) {
                data = v.response.data
            }
            return data
        })
        let picture = arr.join(',')
        this.formRef.setFieldsValue({
            picture
        })
    }
    //表单提交
    saveVehicle = async (value) => {
        if (!value.remark) {
            value.remark = ""
        }
        if (this.state.id === 'add') {
            await apiPostCarInfo(value).then(
                res => {
                    if (res.code === 0) {
                        React.$message({
                            type: 'info',
                            content: "添加车辆成功"
                        })
                        this.props.history.goBack()
                    }
                }
            ).catch(err => {
                React.$message({
                    type: 'warning',
                    content: err.code
                })
            })
        } else {
            value.carId = this.state.id
            await apiPutCarInfo(value).then(
                res => {
                    if (res.code === 0) {
                        React.$message({
                            type: 'info',
                            content: "编辑车辆成功"
                        })
                        this.props.history.goBack()
                    }
                }
            ).catch(err => {
                React.$message({
                    type: 'warning',
                    content: err.code
                })
            })
        }
    }
    //选择司机
    onChange = (value) => {
        this.setState({
            driverId: value
        })
        this.formRef.setFieldsValue({
            driverId: value
        })
    }
    //新建司机弹窗
    addChauffeur = () => {
        this.setState({
            ModalVisible: true
        })
    }
    closeModal = () => {
        this.setState({
            ModalVisible: false
        })
    }
    ModalSumbit = (params) => {
        this.ChauffeurDetailRefs.current.formRef.resetFields()
        this.setState({
            ModalVisible: false
        })
        if (params.type === 'cancel') {


        } else {
            this.getChauffeurList()
        }

    }
    //View
    render() {
        const { visible, content, fileList, btnLoading, chauffeurList, driverId, disabled, picture, ModalVisible } = this.state
        return (
            <div className="missionsPage">
                <GoBack history={this.props.history} title={content} />
                <Form labelCol={{ span: 3, offset: 0 }} wrapperCol={{ span: 6, offset: 1 }} ref={(ref) => (this.formRef = ref)} onFinish={this.saveVehicle} >
                    <div className="title">
                        基础信息 <CaretDownOutlined />
                    </div>
                    <Form.Item label="车辆图片：" name="picture"
                        rules={[{ required: true, message: '请添加车辆图片' }]}>
                        {disabled && <TheImage src={picture} width={100} height={100} />}
                        {!disabled && <TheUpload disabled={disabled} maxSize={10} len={1} fileList={fileList} getFileResult={this.getFileResult} />}
                    </Form.Item>
                    <Form.Item label="车辆品牌：" name="brand"
                        rules={[{ required: true, message: '请填写车辆品牌' }]}>
                        <Input disabled={disabled} placeholder="请输入" maxLength={120} />
                    </Form.Item>
                    <Form.Item label="车辆型号：" name="model"
                        rules={[{ required: true, message: '请填写车辆型号' }]}>
                        <Input disabled={disabled} placeholder="请输入" maxLength={120} />
                    </Form.Item>
                    <Form.Item label="车身颜色：" name="color"
                        rules={[{ required: true, message: '请填写车身颜色' }]}>
                        <Input disabled={disabled} placeholder="请输入" maxLength={120} />
                    </Form.Item>
                    <Form.Item label="车牌号：" name="number" rules={[{ required: true, message: '请添加车牌号' }]}>
                        <Input disabled={disabled} placeholder="请输入" maxLength={120} />
                    </Form.Item>
                    <Form.Item label="所属司机：" name="driverId" rules={[{ required: true, message: '请选择车辆所属司机' }]} >
                        <Space wrap>
                            <Select disabled={disabled} style={{ width: '230px' }} value={driverId}
                                onChange={this.onChange}
                            >
                                {chauffeurList && chauffeurList.map(item => {
                                    return (
                                        <Select.Option value={item.driverId}>{item.nickname}</Select.Option>
                                    )
                                })}
                            </Select>
                            {visible &&
                                <div >
                                    <Space>
                                        <Button onClick={() => this.getChauffeurList()}>刷新</Button>
                                        <Button onClick={() => this.addChauffeur()}>新建司机</Button>
                                    </Space>
                                </div>
                            }
                        </Space>
                    </Form.Item>
                    <Divider />
                    <Form.Item label="备注：" name="remark">
                        <Input.TextArea disabled={disabled} maxLength={200} showCount />
                    </Form.Item>
                    {visible && <Form.Item>
                        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                            <Space>
                                <Button loading={btnLoading} type='primary' htmlType='submit'
                                >保存</Button>
                                <Button onClick={() => this.props.history.goBack()}>取消</Button>
                            </Space>
                        </div>
                    </Form.Item>
                    }
                </Form>
                <Modal width={800} visible={ModalVisible} footer={null}
                    onCancel={() => this.ModalSumbit({ type: "cancel" })}
                >
                    <ChauffeurDetail ref={this.ChauffeurDetailRefs} sumbit={this.ModalSumbit} type="normal" />
                </Modal>
            </div>
        )
    }
}